﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InHD.model;
using InHD.utilities;
using System.Data;
using System.IO;

namespace InHD.dataaccess
{
    class InvoiceTemplateRepository
    {
        #region Fields

        readonly List<InvoiceTemplate> _invoiceTemplate;
        //For DB Utils
        private DBUltils _db;
        string[] _paramName;
        string[] _value;
        DBUltils.ParamType[] _paramType;

        #endregion // Fields

        #region Constructor

        /// <summary>
        /// Creates a new repository of 
        /// </summary>
        public InvoiceTemplateRepository()
        {
            _invoiceTemplate = new List<InvoiceTemplate>();
            this._db = new DBUltils();
            if (!_db.connectDB(Constants.Security.DefaultDBUser, Constants.Security.DefaultDBPassword))
                throw new ArgumentNullException(Constants.Messages.CannotConnectDB);
        }

        #endregion // Constructor

        #region Public Interface

        /// <summary>
        /// Raised when a Transaction is placed into the repository.
        /// </summary>
        public event EventHandler<InvoiceTemplateAddedEventArgs> InvoiceTemplateAdded;
 
        /// <summary>
        /// Returns a shallow-copied list of all Transactions in the repository.
        /// </summary>
        public List<InvoiceTemplate> GetInvoiceTemplate()
        {
            return new List<InvoiceTemplate>(_invoiceTemplate);
        }

        public string LoadAllInvoiceTemplate()
        {
            try
            {
                if (_db == null)
                    throw new ArgumentNullException(Constants.Messages.DBNotInitialized);
                DataSet ds;
                ds = _db.queryDB("GetAllInvoiceFull", _paramName, _paramType, _value, DBUltils.QueryType.Select);
                if (ds != null && ds.Tables[0] != null)
                {
                    this._invoiceTemplate.Clear();
                    DataTable table = ds.Tables[0];
                    foreach (DataRow row in table.Rows)
                    {
                        int tmpID = Convert.ToInt16(row["id"]);
                        string tmpInvoiceUNK = Convert.ToString(row["invoiceUNK"]);
                        string tmpContent = String.Empty;
                        byte[] realContent = !(row["content"] is DBNull) ? (byte [])row["content"] : new byte [1];
                        int tmpModifiedBy = Convert.ToInt16(row["modifiedBy"]);
                        string tmpTransType = Convert.ToString(row["transType"]);
                        string tmpName = Convert.ToString(row["name"]);
                        string tmpCode = Convert.ToString(row["code"]);
                        string tmpArchiveFlag = Convert.ToString(row["archiveFlag"]);
                        DateTime tmpDateTime = Convert.ToDateTime(row["modified"]);
                        this._invoiceTemplate.Add(InvoiceTemplate.CreateNewInvoiceTemplate(tmpID, tmpInvoiceUNK, tmpContent, tmpName, tmpDateTime, tmpModifiedBy, (TransTypes)Enum.Parse(typeof(TransTypes), tmpTransType), tmpCode, realContent, tmpArchiveFlag));
                    }
                }
            }
            catch (Exception e)
            {
                Logger.RecordMessage(e, MessageType.Error);
                return e.Message;
            }
            return string.Empty;
        }

        public string LoadAllUnRegInvoiceTemplate()
        {
            try
            {
                if (_db == null)
                    throw new ArgumentNullException(Constants.Messages.DBNotInitialized);
                DataSet ds;
                ds = _db.queryDB("GetAllUnRegInvoice", _paramName, _paramType, _value, DBUltils.QueryType.Select);
                if (ds != null && ds.Tables[0] != null)
                {
                    this._invoiceTemplate.Clear();
                    DataTable table = ds.Tables[0];
                    foreach (DataRow row in table.Rows)
                    {
                        int tmpID = Convert.ToInt16(row["id"]);
                        string tmpInvoiceUNK = Convert.ToString(row["invoiceUNK"]);
                        string tmpContent = String.Empty;
                        byte[] realContent = row["content"] is DBNull ? new byte[0] : (byte[])row["content"];
                        int tmpModifiedBy = Convert.ToInt16(row["modifiedBy"]);
                        string tmpTransType = Convert.ToString(row["transType"]);
                        string tmpName = Convert.ToString(row["name"]);
                        string tmpCode = Convert.ToString(row["code"]);
                        string tmpArchiveFlag = Convert.ToString(row["archiveFlag"]);
                        DateTime tmpDateTime = Convert.ToDateTime(row["modified"]);
                        this._invoiceTemplate.Add(InvoiceTemplate.CreateNewInvoiceTemplate(tmpID, tmpInvoiceUNK, tmpContent, tmpName, tmpDateTime, tmpModifiedBy, (TransTypes)Enum.Parse(typeof(TransTypes), tmpTransType), tmpCode, realContent, tmpArchiveFlag));
                    }
                }
            }
            catch (Exception e)
            {
                Logger.RecordMessage(e, MessageType.Error);
                return e.Message;
            }
            return string.Empty;
        }

        public string LoadAllInvoiceTplByTransType(TransTypes transType)
        {
            try
            {
                if (_db == null)
                    throw new ArgumentNullException(Constants.Messages.DBNotInitialized);
                DataSet ds;
                _paramName = new string[] { "@transactionType" };
                _paramType = new DBUltils.ParamType[] { DBUltils.ParamType.Str };
                _value = new string[] { transType.ToString() };
                ds = _db.queryDB("GetAllInvoiceByTransType", _paramName, _paramType, _value, DBUltils.QueryType.Select);
                if (ds != null && ds.Tables[0] != null)
                {
                    this._invoiceTemplate.Clear();
                    DataTable table = ds.Tables[0];
                    foreach (DataRow row in table.Rows)
                    {
                        int tmpID = Convert.ToInt16(row["id"]);
                        string tmpInvoiceUNK = Convert.ToString(row["invoiceUNK"]);
                        string tmpContent = String.Empty;
                        byte[] realContent = (byte[])row["content"];
                        int tmpModifiedBy = Convert.ToInt16(row["modifiedBy"]);
                        string tmpTransType = Convert.ToString(row["transType"]);
                        string tmpName = Convert.ToString(row["name"]);
                        string tmpCode = Convert.ToString(row["code"]);
                        string tmpArchiveFlag = Convert.ToString(row["archiveFlag"]);
                        DateTime tmpDateTime = Convert.ToDateTime(row["modified"]);
                        this._invoiceTemplate.Add(InvoiceTemplate.CreateNewInvoiceTemplate(tmpID, tmpInvoiceUNK, tmpContent, tmpName, tmpDateTime, tmpModifiedBy, (TransTypes)Enum.Parse(typeof(TransTypes), tmpTransType), tmpCode, realContent, tmpArchiveFlag));
                    }
                }
            }
            catch (Exception e)
            {
                Logger.RecordMessage(e, MessageType.Error);
                return e.Message;
            }
            return string.Empty;
        }

        public static void AddNewInvoiceTemplate(InvoiceTemplate _invoiceTemplate)
        {
            string storeProName = "AddInvoiceTempl";
            List<string> paramName = new List<string>();
            paramName.Add("@invoiceUNK");
            paramName.Add("@content");
            paramName.Add("@modifyBy");
            paramName.Add("@modifyDate");
            paramName.Add("@name");
            paramName.Add("@code");
            paramName.Add("@tranType");

            byte[] fileContent = null;
            try
            {
                FileStream fileStream = new FileStream(_invoiceTemplate.Content, FileMode.Open, FileAccess.Read);
                System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(fileStream);
                long _TotalBytes = new System.IO.FileInfo(_invoiceTemplate.Content).Length;
                fileContent = _BinaryReader.ReadBytes((Int32)_TotalBytes);
            }
            catch (Exception ex)
            {
            }

            List<object> paramValue = new List<object>();
            paramValue.Add("inv" + Guid.NewGuid().ToString());
            paramValue.Add(fileContent);
            paramValue.Add(1); ////hardCode
            paramValue.Add(DateTime.Now);
            paramValue.Add(_invoiceTemplate.Name);
            paramValue.Add(_invoiceTemplate.Code);
            paramValue.Add(_invoiceTemplate.TransType.ToString());

            try
            {
                int newID = DBUltils.CRUDQuery(storeProName, paramName, paramValue);
            }
            catch (Exception ex)
            {
                ////Handle Exception Here
            }
        }

        public byte[] GetInvoiceContent(string InvoiceUNK)
        {
            try
            {
                byte[] content;
                DataSet ds;
                if (_db == null)
                    return null;
                if (InvoiceUNK == null)
                    return null;
                _paramName = new string[] { "@InvoiceTmplUNK" };
                _paramType = new DBUltils.ParamType[] { DBUltils.ParamType.Str };
                _value = new string[] { InvoiceUNK };

                ds = _db.queryDB("GetInvoiceContent", _paramName, _paramType, _value, DBUltils.QueryType.Select);
                content = (byte[])ds.Tables[0].Rows[0]["content"];
                return content;
            }
            catch (Exception e)
            {
                Logger.RecordMessage(e, MessageType.Error);
                return null;
            }
        }

        public bool DeleteAnInvoiceTemplate(string invoiceTplUNK)
        {
            try
            {
                DataSet ds;
                if (_db == null)
                    return false;
                if (string.IsNullOrEmpty(invoiceTplUNK))
                    return false;
                _paramName = new string[] { "@invoiceTplUNK" };
                _paramType = new DBUltils.ParamType[] { DBUltils.ParamType.Str };
                _value = new string[] { invoiceTplUNK };

                ds = _db.queryDB("[DeleteInvoiceTemplate]", _paramName, _paramType, _value, DBUltils.QueryType.Update);
                return true;
            }
            catch (Exception e)
            {
                Logger.RecordMessage(e, MessageType.Error);
                return false;
            }
        }

        public bool EditAnInvoiceTemplate(InvoiceTemplate _invoiceTpl)
        {
            try
            {
                DataSet ds;
                if (_db == null)
                    return false;
                if (string.IsNullOrEmpty(_invoiceTpl.InvoiceUNK))
                    return false;
                _paramName = new string[] { "@invoiceTplUNK", "@invoiceTplName", "@invoiceTplCode", "@transType" };
                _paramType = new DBUltils.ParamType[] { DBUltils.ParamType.Str, DBUltils.ParamType.NStr, DBUltils.ParamType.Str, DBUltils.ParamType.Str };
                _value = new string[] { _invoiceTpl.InvoiceUNK, _invoiceTpl.Name, _invoiceTpl.Code, _invoiceTpl.TransType.ToString() };

                ds = _db.queryDB("[UpdateInvoiceTemplate]", _paramName, _paramType, _value, DBUltils.QueryType.Update);
                return true;
            }
            catch (Exception e)
            {
                Logger.RecordMessage(e, MessageType.Error);
                return false;
            }
        }
        #endregion // Public Interface
    }
}
